package ch.netcetera.planningpoker.client.ui.events;

import java.util.logging.Level;
import java.util.logging.Logger;

import ch.netcetera.planningpoker.shared.ui.events.GameUiEvent;

import com.google.gwt.appengine.channel.client.SocketError;
import com.google.gwt.appengine.channel.client.SocketListener;
import com.google.web.bindery.event.shared.EventBus;

public class EventSocketListener implements SocketListener {

    private static final Logger logger = Logger
            .getLogger(EventSocketListener.class.getName());

    private EventBus eventbus;

    public EventSocketListener(EventBus eventbus) {
        this.eventbus = eventbus;
    }

    @Override
    public void onMessage(String message) {

        String[] splittedMsg = message.trim().split("_");

        if (splittedMsg.length == 2) {
            Long gameId = Long.valueOf(splittedMsg[1]);

            // find an easier solution instead of a switch?
            switch (GameUiEvent.valueOf(splittedMsg[0])) {

            case UserListChanged:
                eventbus.fireEvent(new UserListChangedEvent(gameId));
                break;

            case RoundStatusChanged:
                eventbus.fireEvent(new RoundStatusChangedEvent(gameId));
                break;

            default:
                logger.warning("Unsupported GameUiEvent-Message received:"
                        + message);

            }

        }
    }

    @Override
    public void onOpen() {
        logger.info("Channel opened: " + this);
    }

    @Override
    public void onError(SocketError error) {
        logger.log(Level.SEVERE, "Channel communication failed: " + error);

    }

    @Override
    public void onClose() {
        logger.info("Channel closed: " + this);

    }

}
